package cn.dengfanxin.gae.test.keyword;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddKeyword extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6867266012800579597L;

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		// get paramaters : time keyword tag level
//		String time = request.getParameter("time");
		String time = new Date().toString();
		String keyword = URLDecoder.decode(request.getParameter("keyword"), "UTF-8");
		String tag = URLDecoder.decode(request.getParameter("tag"),"UTF-8");
		String level = URLDecoder.decode(request.getParameter("level"), "UTF-8");
		
		//test keyword encoding into a file
		
		Keyword key = new Keyword(time, keyword, tag, level);
		System.out.println(key);
		if (!validate(key)) {
			response.sendRedirect("/error.jsp?errormsg="+URLEncoder.encode("Lack primary information of submited keyword", "UTF-8"));
			return;
		}
		//add to db
		PersistenceManager pm = PMF.getInstance().getPersistenceManager();
		try{
			pm.makePersistent(key);
		}finally{
			pm.close();
		}
		
	}

	private boolean validate(Keyword key) {
		if (key.getKeyword() != null) return true;
		return false;
	}

}
